package com.atguigu.educenter.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.utils.ConstansWxUtils;
import com.atguigu.educenter.utils.HttpClientUtils;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/12/14
 */
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;


    //1、生成微信二维码
    @GetMapping("login")
    public String getWxCode() {
        //固定地址，拼接参数
        //微信开放平台授权baseUrl  固定格式
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_url进行URLEncoder编码
        String redirectUrl = ConstansWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            //对URL进行utf-8的编码
            URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = String.format( //向指定字符串中按顺序替换%s
                baseUrl,
                ConstansWxUtils.WX_OPEN_APP_ID,
                ConstansWxUtils.WX_OPEN_REDIRECT_URL,
                "Cyrus"
        );


        //请求微信地址
        return "redirect:" + url;
    }

    //2、扫描人信息，添加数据
    @GetMapping("callback")
    public String callback(String code,String state) {
        //1、获取code值，临时票据、类似于验证码


        //2、拿着code请求微信固定的地址，得到两个值access_token 和 openid
        String baseAccessTokenUrl =
                "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        //3、拼接三个参数：id   密钥   code值
        String accessTokenUrl = String.format(
                baseAccessTokenUrl,
                ConstansWxUtils.WX_OPEN_APP_ID,
                ConstansWxUtils.WX_OPEN_APP_SECRET,
                code
        );

        try {
            //请求这个拼接好的地址，得到两个值access_token 和 openid
            //使用httpClient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println(accessTokenInfo);
            /**
             * 返回的accessTokenInfo字符串
             * {"access_token":"40_pJMXQgV4ZWrAoJbyPB0eJEQ_T_J6gMyjUd-RE0FMtEs26nJXuhtnhIpGXman1j7JgM1KMI7IHdGDomEyMDegcqA3_xye19tYVjTT3MQehXg",
             * "expires_in":7200,
             * "refresh_token":"40_J1OfBDtD4o9jVQ_kznqtQUU3YHE5c41a0mmwwa7YHuzW-ue-xYc90eB-PhYXDl4Zp4T5cd47RSqYsGorvFnFZvipB0ZcEIqhjAweEKZ8DV0",
             * "openid":"o3_SC5_lx2s39V71vJfHDNpZryOs","scope":"snsapi_login","unionid":"oWgGz1OZ4rFmy_loBsH7ag7YJMRY"}
             */
            //使用json转换工具 gson
            Gson gson = new Gson();
            //转换为一个map集合
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");
            //将扫码人信息添加到数据库中
            //首先判断数据库中是否存在相同信息,根据openid进行查询
            UcenterMember member = memberService.getOpenId(openid);
            if (member == null) { //若为空，标识表里没有数据

            //携带access_token，openid请求地址获取微信用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";

            String userInfoUrl = String.format(
                    baseUserInfoUrl,
                    access_token,
                    openid
            );

            String userInfo = HttpClientUtils.get(userInfoUrl);
            System.out.println("userInfo"+userInfo);
            /**
             * 获取微信用户信息
             * userInfo{"openid":"o3_SC5_lx2s39V71vJfHDNpZryOs",
             * "nickname":"川川川川川",
             * "sex":1,
             * "language":"zh_CN",
             * "city":"Neijiang",
             * "province":"Sichuan",
             * "country":"CN",
             * "headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/WkOtDxGMJHIAgztIamokN7wnBhzbxP9KH9gFdIMchoSDAt1tvKzv5VRQ7xiaVbCHNEPddDBkqqopbKCq5Xlffjg\/132",
             * "privilege":[],
             * "unionid":"oWgGz1OZ4rFmy_loBsH7ag7YJMRY"}
             */
            //使用gson来转换格式
            HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
            //用户名
            String nickname = (String) userInfoMap.get("nickname");
            //头像
            String headimgurl = (String) userInfoMap.get("headimgurl");

            //将数据添加到数据库中
            member = new UcenterMember();
            member.setOpenid(openid);
            member.setAvatar(headimgurl);
            member.setNickname(nickname);
            memberService.save(member);
            }
            //使用jwt根据member对象生成token字符串
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            //最终跳转到主页面,通过路径传递token
            return "redirect:http://localhost:3000?token="+jwtToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "扫码登陆失败");
        }
    }
}
